package com.atom.module.mvvm.extren

import android.view.View
import androidx.annotation.CheckResult
import androidx.drawerlayout.widget.DrawerLayout
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun DrawerLayout.drawerStateChanges(gravity: Int) = callbackFlow<Boolean> {
    checkMainThread()
    val listener = object : DrawerLayout.DrawerListener {
        override fun onDrawerOpened(drawerView: View) {
            val drawerGravity = (drawerView.layoutParams as DrawerLayout.LayoutParams).gravity
            if (drawerGravity == gravity) {
                trySend(true)
            }
        }

        override fun onDrawerClosed(drawerView: View) {
            val drawerGravity = (drawerView.layoutParams as DrawerLayout.LayoutParams).gravity
            if (drawerGravity == gravity) {
                trySend(false)
            }
        }

        override fun onDrawerSlide(drawerView: View, slideOffset: Float) = Unit

        override fun onDrawerStateChanged(newState: Int) = Unit
    }
    addDrawerListener(listener)
    awaitClose { removeDrawerListener(listener) }
}
    .conflate()
    .asInitialValueFlow { isDrawerOpen(gravity) }
